package com.vay.de.dang.online;

import android.app.Application;
import android.content.res.Resources;
import android.text.TextUtils;

import com.appsflyer.AppsFlyerConversionListener;
import com.appsflyer.AppsFlyerLib;
import com.vay.de.dang.online.entiy.AppFlyerEventEntity;
import com.vay.de.dang.online.util.VnUtil;
import com.vay.de.dang.online.util.VnDefine;
import com.vay.de.dang.online.util.VnContext;
import com.vay.de.dang.online.util.LocationHelper;
import com.vay.de.dang.online.util.VnPfReader;
import com.vay.de.dang.online.util.VnExecutors;
import com.vay.de.dang.online.util.VnHandler;
import com.vay.de.dang.online.phone.DeviceHelper;
import com.vay.de.dang.online.web.BaseApi;
import com.vay.de.dang.online.web.JsonUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

public class VnApp extends Application {

    static final String FB_AD = "Facebook Ads";
    static final String FB_AD_LIMITED = "restricted";
    static final String GOOGLE_AD = "googleadwords_int";

    private static VnApp _instance;
    private static Resources mResources;
    private static VnPfReader pfReader;
    private static String uuid = "";

    @Override
    public void onCreate() {
        super.onCreate();
        _instance = this;
        uuid = DeviceHelper.uuid();
        mResources = getResources();
        VnPfReader.init(this);
        pfReader = VnPfReader.instance();
        VnExecutors.init();
        VnContext.create(this);

        // location
        LocationHelper.create(this);

        initAppFlyer();
    }

    private void initAppFlyer() {
        AppsFlyerConversionListener conversionListener = new AppsFlyerConversionListener() {

            @Override
            public void onConversionDataSuccess(Map<String, Object> conversionData) {

                BaseApi.log("--------Af---------");
                Set<String> keys = conversionData.keySet();
                for (String key : keys) {
                    BaseApi.log("Af: key=" + key + ";     v=" + conversionData.get(key));
                }

                String status = Objects.requireNonNull(conversionData.get("af_status")).toString();
                if (status.equals("Non-organic")) {
                    if (Objects.requireNonNull(conversionData.get("is_first_launch")).toString().equals("true")) {
                        String mediaSource = Objects.requireNonNull(conversionData.get("media_source")).toString();
                        //campaign 存在值为“None”的情况
                        String campaign = (String) conversionData.get("campaign");
                        if (TextUtils.isEmpty(campaign) || "None".equals(campaign)) {
                            campaign = "null";
                        }
                        if (FB_AD.equals(mediaSource) || FB_AD_LIMITED.equals(mediaSource)) {
                            String adgroup = TextUtils.isEmpty((String) conversionData.get("adgroup")) ? "null" : (String) conversionData.get("adgroup");
                            String ad_id = TextUtils.isEmpty((String) conversionData.get("ad_id")) ? "null" : (String) conversionData.get("ad_id");
                            pfReader.putString(VnDefine.SP_KEY_INSTALL_CHANNEL, String.format("%s#%s/%s/%s", mediaSource, campaign, adgroup, ad_id));
                        } else if (GOOGLE_AD.equals(mediaSource)) {
                            String af_channel = TextUtils.isEmpty((String) conversionData.get("af_channel")) ? "null" : (String) conversionData.get("af_channel");
                            String network = TextUtils.isEmpty((String) conversionData.get("network")) ? "null" : (String) conversionData.get("network");
                            pfReader.putString(VnDefine.SP_KEY_INSTALL_CHANNEL, String.format("%s#%s/%s/%s", mediaSource, campaign, af_channel, network));
                        } else {
                            pfReader.putString(VnDefine.SP_KEY_INSTALL_CHANNEL, String.format("%s#%s", mediaSource, campaign));
                        }
                    }
                } else {
                    pfReader.putString(VnDefine.SP_KEY_INSTALL_CHANNEL, VnDefine.AF_STORE);
                }

                // 硬件标识符的抓取
                String afAndroidId = readAfString(conversionData.get("android_id"));
                String afAdId = readAfString(conversionData.get("advertising_id"));
                if (!TextUtils.isEmpty(afAndroidId)) {
                    pfReader.putString(VnDefine.SP_AF_COLLECT_ANDROID_ID, afAndroidId);
                }
                if (!TextUtils.isEmpty(afAdId)) {
                    pfReader.putString(VnDefine.SP_AF_COLLECT_AD_ID, afAdId);
                }

                // 初始埋点的信息抓取
                String installTime = readAfString(conversionData.get("install_time"));
                boolean isFirstLaunch = readAfBoolean(conversionData.get("is_first_launch"));
                AppFlyerEventEntity base = new AppFlyerEventEntity();
                base.setApkPackage(getPackageName());
                base.setInstallTime(installTime);
                base.setFirstLaunch(isFirstLaunch);
                base.setInstallChannel(pfReader.readString(VnDefine.SP_KEY_INSTALL_CHANNEL));
                pfReader.putString(AppFlyerEventEntity.class.getSimpleName(), JsonUtil.objectToJson(base));

                if (!pfReader.readBoolean(VnDefine.KeyFirst)) {
                    VnHandler.runUIDelayed(() -> {
                        Map<String, Object> param = new HashMap<>();
                        param.put("appflyerId", VnDefine.APPFLYER_ID);
                        param.put("androidId", getAfAndroidId());
                        param.put("uuid", uuid);
                        trackEventParam("startSuccess", param);
                        pfReader.putBoolean(VnDefine.KeyFirst, true);
                    }, 1000);
                }
            }

            @Override
            public void onConversionDataFail(String s) {

            }

            @Override
            public void onAppOpenAttribution(Map<String, String> map) {

            }

            @Override
            public void onAttributionFailure(String s) {

            }
        };
        AppsFlyerLib.getInstance().waitForCustomerUserId(true);

        /* This API enables AppsFlyer to detect installations, sessions, and updates. */
        AppsFlyerLib.getInstance().init(VnDefine.APPFLYER_ID, conversionListener, this);
        AppsFlyerLib.getInstance().setCollectAndroidID(true);
        AppsFlyerLib.getInstance().setCollectIMEI(true);
        AppsFlyerLib.getInstance().setCollectOaid(true);
        AppsFlyerLib.getInstance().start(this);
        AppsFlyerLib.getInstance().setDebugLog(BuildConfig.DEBUG);
        AppsFlyerLib.getInstance().setCustomerIdAndLogSession(uuid, this);
    }

    private static String readAfString(Object value) {
        return value != null ? value.toString() : "";
    }

    private static boolean readAfBoolean(Object value) {
        return value != null ? (Boolean) value : false;
    }

    // 其他
    public static void trackEventParam(String eventName, Map<String, Object> param) {
        VnPfReader pfReader = VnPfReader.instance();
        String json = pfReader.readString(AppFlyerEventEntity.class.getSimpleName());
        AppFlyerEventEntity base = JsonUtil.jsonToObject(json, AppFlyerEventEntity.class);
        if (null != base) {
            Map<String, Object> map = base.transferMap();
            if (param != null) {
                Set<String> keys = param.keySet();
                for (String key : keys) {
                    map.put(key, param.get(key));
                }
            }
            AppsFlyerLib.getInstance().logEvent(_instance, eventName, map);
        }
    }

    // 首页曝光
    public static void trackEventHomeExposure() {
        if (!pfReader.readBoolean(VnDefine.KeyHomeExposure)) {
            Map<String, Object> param = new HashMap<>();
            param.put("appflyerId", VnDefine.APPFLYER_ID);
            trackEventParam("homeExposure", param);
            pfReader.putBoolean(VnDefine.KeyHomeExposure, true);
        }
    }

    // 首代提交成功
    public static void trackEventFirstOrder() {
        VnPfReader pfReader = VnPfReader.instance();
        String json = pfReader.readString(AppFlyerEventEntity.class.getSimpleName());
        AppFlyerEventEntity base = JsonUtil.jsonToObject(json, AppFlyerEventEntity.class);
        if (null != base) {
            Map<String, Object> map = base.transferMap();
            map.put("appflyerId", VnDefine.APPFLYER_ID);
            map.put("userId", VnContext.instance().getUserId());
            AppsFlyerLib.getInstance().logEvent(_instance, "firstSubmitOrderSuccess", map);
        }
    }

    // 非首代提交成功
    public static void trackEventOrder() {
        VnPfReader pfReader = VnPfReader.instance();
        String json = pfReader.readString(AppFlyerEventEntity.class.getSimpleName());
        AppFlyerEventEntity base = JsonUtil.jsonToObject(json, AppFlyerEventEntity.class);
        if (null != base) {
            Map<String, Object> map = base.transferMap();
            map.put("appflyerId", VnDefine.APPFLYER_ID);
            map.put("userId", VnContext.instance().getUserId());
            AppsFlyerLib.getInstance().logEvent(_instance, "nonFirstSubmitOrderSuccess", map);
        }
    }

    public static int getScreenWidth() {
        return mResources.getDisplayMetrics().widthPixels;
    }

    public static int getScreenHeight() {
        return mResources.getDisplayMetrics().heightPixels;
    }

    public static int getDimension(int rid) {
        return mResources.getDimensionPixelSize(rid);
    }

    public static String getAfAndroidId() {
        String afAndroidId = pfReader.readString(VnDefine.SP_AF_COLLECT_ANDROID_ID);
        if (TextUtils.isEmpty(afAndroidId) || afAndroidId == "null") {
            return DeviceHelper.getAndroidId(instance());
        } else {
            return afAndroidId;
        }
    }

    public static String getGoogleAdId() {
        return pfReader.readString(VnDefine.SP_AF_COLLECT_AD_ID);
    }

    public static String getChannel() {
        String channel = pfReader.readString(VnDefine.SP_KEY_INSTALL_CHANNEL);
        return VnUtil.isEmpty(channel) ? "GooglePlay" : channel;
    }

    public static String getUuid() {
        return uuid;
    }

    public static String getStr(int rid) {
        return mResources.getString(rid);
    }

    public static VnApp instance() {
        return _instance;
    }
}
